from easygui import *
from time import *
import sys
import cPAMIE as PAMIE
import cReport


# Initialize our stuff.
rep = cReport.Report()
rep.initialize()
ie = PAMIE.PAMIE()
ie.showDebugging = True
rep.status ("Starting...")

# global variables
USR = None
PAS = None
TO = None
MSG = None
remainingSMS = None

sumUSR = str(USR)
sumMSG= str(MSG)
sumTO= str(TO)
sumRemainingSMS = str(remainingSMS)
currentTime = strftime("%H:%M:%S", localtime())
currentDate = strftime("%a, %d %b %Y", localtime())
reportMe = "\n\n\nReport bugs and any vodafone.ie changes to darren.mcentee@gmail.com"
rep.status ("Globals initiated...")

#-----------------------------------
# Simple intro Message box function.
#

def msgboxOpen(message="Please make sure there is an internet connection available!", title="VODApp", buttonMessage="Continue"):
	rep.status ("*** DEBUG: in msgBox()")
	choices = [buttonMessage]
	reply = buttonbox(message, title, choices)
	return reply

#-----------------------------------
# Simple Info Message box function: a summary of data entered and used by vodafone.
#

def msgboxSummary(message="Summary details", title="VODApp", text=[]):
	global sumUSR, sumMSG, sumTO, currentTime, currentDate, reportMe, sumRemainingSMS
	sumUSR = str(USR)
	sumMSG = str(MSG)
	sumTO = str(TO)
	sumRemainingSMS = str(remainingSMS)
	
	
	text=["A summary of the details you sent...\n\n",
		  "\t\n - Date: \t", currentDate,
		  "\t\n - Time: \t", currentTime,
		  "\t\n - From: \t",sumUSR,
		  "\t\n - To:   \t", sumTO,
		  "\t\n - Message: \t", sumMSG,
		  "\t\n - SMS left: \t", sumRemainingSMS,
		  "\n\n - Logging off...",
		  "\n\nYou have successfully logged out of vodafone.ie\n\n", reportMe]
	textbox(message, title, text, codebox=1 )

		
	try:								# <--- write logs to VODApp.log, in [current run dir]
		file = open("VODApp.log", "w")
		file.write(str(currentTime))
		file.write("\n~~~~~~~~~~~~~~ LOG-START ~~~~~~~~~~~~~~\n")
		file.write(str(text[0]))
		file.write(str(text[1]))
		file.write(str(text[2]))
		file.write(str(text[3]))
		file.write(str(text[4]))
		file.write(str(text[5]))
		file.write(str(text[6]))
		file.write(str(text[7]))
		file.write(str(text[8]))
		file.write(str(text[9]))
		file.write(str(text[10]))
		file.write(str(text[11]))
		file.write(str(text[12]))
		file.write(str(text[13]))
		file.write("\n~~~~~~~~~~~~~~ LOG-END ~~~~~~~~~~~~~~\n")
		file.write(str(currentTime))
		file.close()
	except:
		print 'Error - writing log to file!'

#-----------------------------------
# The User & Pass GUI function.
#

def UserPassGUI():  						# <---- define our vodafone sign in Function
	rep.status("*** DEBUG: in UserPassGUI()")
	try:
#		while 1:
			msg = "VODApp will logon to www.vodafone.ie with your account details and attempt to send an SMS via your web account. Please fill in all fields!"
			title = "VODApp"
			
			fieldNames = ["User Name (#)","Password"]
			fieldValues = []  # we start with blanks for the values
			fieldValues = multpasswordbox(msg,title, fieldNames)
			
			# make sure that none of the fields was left blank
			while 1:
			    if fieldValues == None: break
			    errmsg = ""
			    for i in range(len(fieldNames)):
				    if fieldValues[i].strip() == "":
					    errmsg = errmsg + ('"%s" is a required field.\n' % fieldNames[i])
			    if errmsg == "": break # no problems found
			    fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
		

			global USR, PAS 
			USR = fieldValues[0]
			PAS = fieldValues[1]
			print "\t *** User:", USR
#			print "\t *** Pass:", PAS

	except:
		print 'GUI USER&PASS: QUIT!'



#-----------------------------------
# The MSG GUI function.
#

def MsgGUI():  #define our vodafone sign in Function
	rep.status("*** DEBUG: in MsgGUI()")
	try:
#		while 1:
			msg = "Enter SMS data.\n"
			title = "VODApp"
			msglimit =160
			fieldNames = ["Recipient","SMS Message"]
			fieldValues = []  # we start with blanks for the values
			fieldValues = multenterbox(msg,title, fieldNames)
			
			# make sure that none of the fields was left blank
			while 1:
			    if fieldValues == None: break
			    errmsg = ""
			    for i in range(len(fieldNames)):
				    if fieldValues[i].strip() == "":
					    errmsg = errmsg + ('"%s" is a required field.\n' % fieldNames[i])
			    if errmsg == "": break # no problems found
			    fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)

			global TO, MSG 
			TO = fieldValues[0]
			MSG = fieldValues[1]

			print "\t *** Recipient:", TO
			print "\t *** Message  :", MSG
	
	except:
		print 'GUI MSG: QUIT!'



#-----------------------------------
# The signIn function Class.
#

def signIn():  #define our vodafone sign in Function
	global remainingSMS
	rep.status("*** DEBUG: in signIn()")
	rep.status ("Signing In with details...")
	try:
		print "\t *** User:", USR
		# print "\t *** Pass:", PAS			
		ie.navigate("www.vodafone.ie/services/messaging/webtext/index.jsp")
		rep.status ("URL Opened.")
		rep.status ("Entered User and Pass...")

		rep.verify ("username", ie.textBoxSet("username", USR), True)
		rep.status ("Username: OK!")
		rep.verify ("password", ie.textBoxSet("password", PAS), True)
		rep.status ("Password: OK!")
		
		myElement = ie.elementFind("input", "alt", "Submit")
		ie.elementClick(myElement)
		rep.status ("Login: OK!")

		try:
			ie.linkClick ("Web texts:")
			rep.status ("Selected 'Web texts' URL.")
			

			myElement = ie.elementFind("TEXTAREA", "name", "A46e58445103414217")		# <-- # N.B vodafone forms may have dynamic names, if so get the form name eachtime and store it.
			ie.elementClick(myElement)  			# selects the textbox...
			rep.status ("Found and selected SMS AREA.")

			
			# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ENTER YOUR DATA HERE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			# ... global remainingSMS
			# myElement = ie.elementFind("input", "name", "num")  	# <-- get the sms count field.
			# remainingSMS = ie.elementGetValue(myElement, "value")	# <-- gets the value of the remaining SMS 'chars'

                        
			# Sets the text of [ID] box
			ie.textAreaSet("A46e58445103414217", MSG)		# <---- SMS Message placed into box id: 'A46e58445103414217'
			rep.status ("Entered SMS 'Test' in text area.")

			myElement = ie.elementFind("input", "name", "a0f05090a010004021")
			ie.elementClick(myElement)  					# <---- selects the nuberbox...
			rep.status ("Found and selected Number AREA.")
			ie.textBoxSet("a0f05090a010004021", TO)			# <---- recipient # placed into box id: 'a0f05090a010004021'
			rep.status ("Entered recipient's number.")

			
			rep.status ("Retreiving SMS counter value...")
			remainingSMS = ie.elementFindByIndex("b", 0)		# <-- finds the first <b> (BOLD) element on page. 
			remainingSMS = int(remainingSMS.innerText)		# Our smscounter is the next element. (index of 0 i.e. first element)
			rep.status ("Got remaining SMS counter value.")	        # This may break if the webpage is changed in the slightest.

                                    
			myElement = ie.elementFind("input", "alt", "Send Now")
			rep.status ("Found and selected Send button.")

			ie.elementClick(myElement)
			rep.status ("SMS Sent !")
			rep.status ("Message was:")
			rep.status (MSG)

			# logging off each time.
			ie.navigate("https://www.vodafone.ie/myv/services/logout/Logout.shtml")	# <--- going to Logout.shtml will automatically call the logout.jsp script. this prevents a re-login error, when trying to login when user is already logged in
			rep.status ("Hit Logoff Button...")
			rep.status ("You have successfully logged out. \nQuit!")

			
		except:
			print 'Error inputing data on SMS page!'
			
	except:
		print 'Login: FAILED'




#-----------------------------------
# The MAIN() function.
#

if __name__ == '__main__':
	msgboxOpen()		# call the opening box
	UserPassGUI()		# call the UserPassGUI
	MsgGUI()		# call the startGUI function
	signIn() 		# call the signIn function
	msgboxSummary()		# call the msgboxSummary function: a summary of data entered and used by vodafone.

